<?php

namespace Biz\Jobs;

use Biz\Models\App\AppSite;
use Biz\Models\Site\SiteMail;
use Biz\Mailers\Site\SiteMailer;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Biz\Criteria\Site\SiteFilterCriterion;
use Biz\Repositories\Site\SiteMailRepository;

/**
 * SiteEmailSendJob.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class SiteEmailSendJob extends Job
{
    /**
     * Mail.
     *
     * @var SiteMailer
     */
    public $mail;

    /**
     * Create a new job instance.
     *
     * @param SiteMailer $mail
     *
     * @return SiteEmailSendJob
     */
    public function __construct(SiteMailer $mail)
    {
        $this->mail = $mail;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->applySiteMailConfig();

        Mail::send($this->mail);
    }

    /**
     * Init Site Email.
     */
    public function applySiteMailConfig()
    {
        $appSite = $this->mail->getAppSite();

        if ($appSite instanceof AppSite) {
            $repository = new SiteMailRepository();
            $mail       = $repository
                ->pushCriterion(new SiteFilterCriterion($appSite->id))
                ->findFirst();

            if ($mail instanceof SiteMail) {
                $config = [
                    'driver'     => $mail->driver,
                    'host'       => $mail->host,
                    'port'       => $mail->port,
                    'from'       => $mail->from,
                    'encryption' => $mail->encryption,
                    'username'   => $mail->username,
                    'password'   => $mail->password,
                ];

                app('config')->set('mail', $config);
                Log::debug('SiteEmailSendJob applySiteMailConfig Success');
            }
        }
    }
}
